package com.ruoyi.framework.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许任何域名使用
        corsConfiguration.addAllowedOriginPattern("*");
        // 允许任何请求头
        corsConfiguration.addAllowedHeader("*");
        // 允许任何方法（POST、GET 等）
        corsConfiguration.addAllowedMethod("*");
        // 允许携带凭证（如 cookie）
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean(name = "apiCorsFilter")
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有接口都有效
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}